package com.ld.security.common.shiro.Interceptor;

import com.ld.security.common.core.exception.ApiException;
import com.ld.security.common.shiro.anno.IgnoreUserToken;
import com.ld.security.common.shiro.constants.ShiroCacheConstants;
import com.ld.security.common.shiro.token.JwtToken;
import com.ld.security.common.shiro.util.SessionUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor extends BaseInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Subject subject =  SecurityUtils.getSubject();
        if(!subject.isAuthenticated()){
            String token = SessionUtil.getHeader(ShiroCacheConstants.tokenKey);
            if(token != null){
                JwtToken jwtToken =   new JwtToken(SessionUtil.getIPAddress(),token);
                subject.login(jwtToken);
            }else{
                ApiException.throw401("请获取授权token后再尝试访问");
            }
        }

        return true;
    }

    @Override
    public String getName() {
        return "jwt";
    }
}
